<template>
  <div class="ele-singleUpload">
    <el-upload
      class="avatar-uploader"
      action=""
      :http-request="submitUpload"
      :show-file-list="false"
    >
      <img v-if="coverUrl" :src="coverUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
</template>

<script setup lang="ts">
import type { UploadRequestOptions } from "element-plus"
import { messageReminder } from "@/utils/notificationHint"
import { uploadImageInCommunity } from "@/service/file/uploadFile"

import { ref } from "vue"

interface IProps {
  uploadFolder: string
}
const props = withDefaults(defineProps<IProps>(), {})

const coverUrl = ref("")

/**
 * 上传封面
 * @param content
 */
async function submitUpload(content: UploadRequestOptions) {
  console.log("上传", content)
  const maxSize = 5
  // 判断图片大小
  if (content.file.size / 1024 / 1024 > maxSize) {
    messageReminder({
      message: "图片大小不能超过" + maxSize + "MB",
      type: "info"
    })
    return
  }

  // 创建一个FormData对象，用于封装表单数据
  const formData = new FormData()
  formData.append("singleFile", content.file)
  // 发送上传请求
  let result = await uploadImageInCommunity(formData, props.uploadFolder)
  console.log(result)
  if (result.data.code == 200) {
    console.log("上传成功")
    // success(result.data.data)
    coverUrl.value = result.data.data
  } else {
    messageReminder({
      message: "上传失败！" + result.data.message,
      type: "info"
    })
  }
}

defineExpose({
  coverUrl
})
</script>

<style scoped>
/* 上传图片的样式 */
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
